package com.woorigil.social.parser.coupang;

import java.io.IOException;
import java.io.Reader;
import java.util.List;

import nu.xom.Builder;
import nu.xom.Document;
import nu.xom.Element;
import nu.xom.Elements;
import nu.xom.ParsingException;
import nu.xom.ValidityException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.woorigil.social.DateUtils;
import com.woorigil.social.DiscountUtils;
import com.woorigil.social.domain.ProviderCode;
import com.woorigil.social.domain.deal.Deal;
import com.woorigil.social.domain.deal.DealListDocument;
import com.woorigil.social.domain.deal.ManageStatus;
import com.woorigil.social.parser.XmlParser;

@Component (value="coupangXmlParser")
public class CoupangXmlParser extends XmlParser {
	private static Logger log = LoggerFactory.getLogger(CoupangXmlParser.class);
	
	@Value("${coupang.deal.path}") 
	String dealPath;
	
	@Autowired CoupangXmlShoppingParser shoppingParser;
	

	@Override
	public DealListDocument parse(Reader reader) throws ValidityException, ParsingException, IOException {
		Builder builder = new Builder();
		Document doc = builder.build(reader);
		Element root = doc.getRootElement();
		
		String resultStatus = getValue(root.getFirstChildElement("status"));
		
		if (!"SUCCESS".equals(resultStatus)) {
			throw new IllegalStateException(getValue(root.getFirstChildElement("message")));
		}
		
		DealListDocument dealListDocument = new DealListDocument();
		dealListDocument.setSourceProvider(getValue(root.getFirstChildElement("name")));
		dealListDocument.setVersion(getValue(root.getFirstChildElement("version")));
		dealListDocument.setHomepage(getValue(root.getFirstChildElement("url")));
		dealListDocument.setLogo(getValue(root.getFirstChildElement("logo_img")));
		
		Element dealsEle = root.getFirstChildElement("deals");
		Elements dealsEles = dealsEle.getChildElements();
		for (int i = 0; i < dealsEles.size(); i++) {
			Element dealEl = dealsEles.get(i);

			Deal deal = new Deal();
			deal.setProviderCode(getProviderCode());
			deal.setMetaId(getValue(dealEl.getFirstChildElement("deal_id")));
			deal.setCategory(getValue(dealEl.getFirstChildElement("category1")));
			deal.setSection1(getValue(dealEl.getFirstChildElement("category2")));
			deal.setSection2(getValue(dealEl.getFirstChildElement("category3")));
			deal.setSection3(getValue(dealEl.getFirstChildElement("category4")));
			deal.setSection4(getValue(dealEl.getFirstChildElement("category5")));
			deal.setSaleStartAt(DateUtils.toDate(getValue(dealEl.getFirstChildElement("sale_start_at")), "yyyyMMddHHmmss"));
			deal.setSaleEndAt(DateUtils.toDate(getValue(dealEl.getFirstChildElement("sale_end_at")), "yyyyMMddHHmmss"));
			deal.setUseStartAt(getValue(dealEl.getFirstChildElement("use_start_at")));
			deal.setUseEndAt(getValue(dealEl.getFirstChildElement("use_end_at")));
			deal.setTitle(getValue(dealEl.getFirstChildElement("title")));
			deal.setWebLink(getValue(dealEl.getFirstChildElement("web_link")));
			deal.setMobileLink(getValue(dealEl.getFirstChildElement("mobile_link")));
			deal.setOriginalPrice(Integer.parseInt(getValue(dealEl.getFirstChildElement("original_price"))));
			deal.setSalesPrice(Integer.parseInt(getValue(dealEl.getFirstChildElement("sale_price"))));
			deal.setDiscountRate(DiscountUtils.getRate(deal.getOriginalPrice(), deal.getSalesPrice()));
			deal.setMaxCount(Integer.parseInt(getValue(dealEl.getFirstChildElement("max_count"))));
			deal.setMinCount(Integer.parseInt(getValue(dealEl.getFirstChildElement("min_count"))));
			deal.setNowCount(Integer.parseInt(getValue(dealEl.getFirstChildElement("now_count"))));
			
			deal.setImageUrl1(getValue(dealEl.getFirstChildElement("image6")));
			deal.setImageUrl2(getValue(dealEl.getFirstChildElement("image2")));
			
			deal.setShopName(getValue(dealEl.getFirstChildElement("shop_name")));
			deal.setShopAddress(getValue(dealEl.getFirstChildElement("shop_address")));
			deal.setShopTelephone(getValue(dealEl.getFirstChildElement("shop_telephone")));
			deal.setShopLatitude(getValue(dealEl.getFirstChildElement("shop_latitude")));
			deal.setShopLongitude(getValue(dealEl.getFirstChildElement("shop_longitude")));

			deal.setImageUrl(deal.getImageUrl2());
			deal.setAverageCount((int)(deal.getNowCount() / DateUtils.getTodayCount(deal.getSaleStartAt())));
			deal.setManageStatus(ManageStatus.S);
			deal.setCategoryId(findCategoryId(getProviderCode(), deal));
			dealListDocument.add(deal);
		}
		
		try {
			List<Deal> shoppingDeals = shoppingParser.parse();
			
			for (Deal each : shoppingDeals) {
				dealListDocument.add(each);
			}
		} catch (Exception e) {
			log.error("할인쿠폰 이용권 파싱하다가 에러 발생", e);
		}
		
		log.info(getProviderCode() + " deal size : " + dealListDocument.getDeals().size());

		return dealListDocument;
	}
	
	@Override
	public String getCharsetName() {
		return "UTF-8";
	}

	@Override
	public ProviderCode getProviderCode() {
		return ProviderCode.CP;
	}
	
	@Override
	public String getSourcePath() {
		return dealPath;
	}	
}
